#!/bin/sh
#
# Fork https://github.com/michaelliao/itranswarp.js/blob/master/conf/ssl/gencert.sh

# install expect
which expect >/dev/null 2>&1 || yum install -y expect

# create self-signed server certificate:
read -p "Enter your domain [www.example.com]: " DOMAIN

# certificate info
SUBJECT="/C=CN/ST=HuBei/L=WuHan/O=ldap/OU=ldap/CN=$DOMAIN"

/usr/bin/expect -c "
set timeout 10

spawn echo 'Create server key...'
spawn openssl genrsa -des3 -out $DOMAIN.key 2048
expect {
    key: {
        send \"123456\r\"
        exp_continue
    }
}

spawn echo 'Create server certificate signing request...'
spawn openssl req -new -subj $SUBJECT -key $DOMAIN.key -out $DOMAIN.csr
expect {
    key: {
        send \"123456\r\"
        exp_continue
    }
}

spawn echo 'Remove password...'
spawn mv $DOMAIN.key $DOMAIN.origin.key
spawn openssl rsa -in $DOMAIN.origin.key -out $DOMAIN.key
expect {
    key: {
        send \"123456\r\"
        exp_continue
    }
}
"

echo "Sign SSL certificate..."
openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt

echo "---------------------------------------------------------------------------"
echo "TODO:"
echo
echo "Copy $DOMAIN.crt to /etc/nginx/ssl/$DOMAIN.crt"
echo "Copy $DOMAIN.key to /etc/nginx/ssl/$DOMAIN.key"
echo
echo "Add configuration in nginx:"
echo "server {"
echo "    ..."
echo "    listen 443 ssl;"
echo "    ssl_certificate     /etc/nginx/ssl/$DOMAIN.crt;"
echo "    ssl_certificate_key /etc/nginx/ssl/$DOMAIN.key;"
echo "}"
